from flask import Blueprint, request, jsonify
from flask_login import login_user, logout_user
from app.services.auth_service import AuthService

auth_bp = Blueprint('auth', __name__)
auth_service = AuthService()

@auth_bp.route('/register', methods=['POST'])
def register():
    data = request.json
    user = auth_service.register(data.get('name'), data.get('email'), data.get('password'))
    if not user:
        return jsonify({"error": "Email already exists"}), 400
    return jsonify({"id": user.id, "name": user.name}), 201

@auth_bp.route('/login', methods=['POST'])
def login():
    data = request.json
    user = auth_service.validate_credentials(data.get('email'), data.get('password'))
    if user:
        login_user(user)
        return jsonify({"message": "Login successful"}), 200
    return jsonify({"error": "Invalid credentials"}), 401

@auth_bp.route('/logout')
def logout():
    logout_user()
    return jsonify({"message": "Logged out"}), 200
